#用于访问火币现货的rest api
from lib.utilHuobi import send2api, httpRequest
from lib.settings import HUOBI_API_URL
import config


class Huobi(object):
    def __init__(self):
        self.__url = HUOBI_API_URL['host'] #url使用HUOBI_API_URL['host']
        self.__apikey = config.HUOBI_API_KEY
        self.__secretkey = config.HUOBI_SECRET_TOKEN
        self.fee = HUOBI_API_URL['fee']

        self.btc_free = 0.0  # 账户情况
        self.btc_frozen = 0.0
        self.cny_free = 0.0
        self.cny_frozen = 0.0

        self.bid = 0.0  # 买一卖一情况
        self.bid_volume = 0.0
        self.ask = 0.0
        self.ask_volume = 0.0

    '''
    更新火币现货市场深度
    '''
    def update_depth(self):
        # 更新深度之前，先将上一次的深度置零
        self.bid = 0.0
        self.bid_volume = 0.0
        self.ask = 0.0
        self.ask_volume = 0.0
        try:
            response = httpRequest(HUOBI_API_URL['depth'], '')
            if response == False: #如果更新深度出错，则将盘口信息置为零，不允许交易
                return False

            if 'error' in response or 'code' in response:
                return False
            self.bid = response['bids'][0][0]
            self.bid_volume = response['bids'][0][1]
            self.ask = response['asks'][0][0]
            self.ask_volume = response['asks'][0][1]
            return True
        except Exception as e:
            print(self.__class__.__name__ + ' update_depth error: ' + str(e))
            return False

    '''
    更新用户现货账户信息
    '''
    def update_accountInfo(self):
        # 更新账户资产之前，先将之前的置零
        self.btc_free = 0.0
        self.btc_frozen = 0.0
        self.cny_free = 0.0
        self.cny_frozen = 0.0
        try:
            params = {"method": HUOBI_API_URL['account_info']}
            extra = {}
            response = send2api(params, extra, self.__apikey, self.__secretkey)
            if response == False: #如果更新账户信息出错，则将用户资产置为零，不允许交易
                return False
            if 'error' in response or 'code' in response:
                return False
            self.btc_free = float(response['available_btc_display'])
            self.btc_frozen = float(response['frozen_btc_display'])
            self.cny_free = float(response['available_cny_display'])
            self.cny_frozen = float(response['frozen_cny_display'])
            return True
        except Exception as e:
            print(self.__class__.__name__ + ' update_accountInfo error: ' + str(e))
            return False

    '''
    买入比特币
    '''
    def buy(self, price, amount):
        try:
            params = {"method": HUOBI_API_URL['buy']}
            params['coin_type'] = 1
            params['price'] = price
            params['amount'] = amount
            extra = {}
            response = send2api(params, extra, self.__apikey, self.__secretkey)
            if not response:
                return False
            if 'error' in response or 'code' in response:
                return False
            return str(response['id'])
        except Exception as e:
            print(self.__class__.__name__ + ' buy error: ' + str(e))
            return False

    '''
    卖出比特币
    '''
    def sell(self, price, amount):
        try:
            params = {"method": HUOBI_API_URL['sell']}
            params['coin_type'] = 1
            params['price'] = price
            params['amount'] = amount
            extra = {}
            response = send2api(params, extra, self.__apikey, self.__secretkey)
            if not response:
                return False
            if 'error' in response or 'code' in response:
                return False
            return str(response['id'])
        except Exception as e:
            print(self.__class__.__name__ + ' sell error: ' + str(e))
            return False

    '''
    现货订单查询
    '''
    def order_info(self, orderId):
        try:
            if not orderId:
                return False
            params = {"method": HUOBI_API_URL['order_info']}
            params['coin_type'] = 1
            params['id'] = orderId
            extra = {}
            response = send2api(params, extra, self.__apikey, self.__secretkey)
            if not response:
                return False
            if 'error' in response or 'code' in response:
                return False
            if response['status'] in (0, 1, 5, 7):
                return 'cancelable'
            else:
                return 'ircancelable'
        except Exception as e:
            print(self.__class__.__name__ + ' order_info error: ' + str(e))
            return False

    '''
    查询现货未成交订单
    '''
    def get_orders(self):
        try:
            params = {"method": HUOBI_API_URL['get_orders']}
            params['coin_type'] = 1
            extra = {}
            response = send2api(params, extra, self.__apikey, self.__secretkey)
            if not response:
                return False
            if 'error' in response or 'code' in response:
                return False
            return response
        except Exception as e:
            print(self.__class__.__name__ + ' get_orders error: ' + str(e))
            return False

    '''
    取消订单
    '''
    def cancel_order(self, orderId):
        try:
            if not orderId:
                return False
            params = {"method": HUOBI_API_URL['cancel_order']}
            params['coin_type'] = 1
            params['id'] = orderId
            extra = {}
            response = send2api(params, extra, self.__apikey, self.__secretkey)
            if not response:
                return False
            if 'error' in response or 'code' in response:
                return False
            if response['result'] == 'success':
                return True
            else:
                return False
        except Exception as e:
            print(self.__class__.__name__ + ' cancel_order error: ' + str(e))
            return False

    '''
    取消所有未成交订单
    '''
    def cancel_all(self):
        response = self.get_orders()

        if not response:
            return False

        for order in response:
            self.cancel_order(order['id'])
